package com.itheima.health.service.impl;

import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.service.ReportService;
import com.itheima.health.util.ParseDateUtils;
import com.itheima.health.vo.BusinessReport;
import com.itheima.health.vo.Date_MemberCount;
import com.itheima.health.vo.Setmeal_Proportion;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.InputStream;
import java.sql.Date;
import java.util.Calendar;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    /**
     * 计算12月前会员数
     */
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private OrderDao orderDao;

    @Override
    public Integer memberCountBefore12Month() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), (calendar.get(Calendar.MONTH) - 11), 1);
        Date date = new Date(calendar.getTime().getTime());
        Integer count = memberDao.countMemberByDate(date);
        return count;
    }

    /**
     * 计算这一年来 每个月新增的会员数
     *
     * @return
     */
    @Override
    public List<Date_MemberCount> memberCountByMonth() {
        List<Date_MemberCount> list = memberDao.memberCountByMonth();
        //在这里进行每个月会员数量的统计 截止本月会员数量= 前一个月会员数量+本月新增
        //定义截止上个月会员数量 从 redis中取出来
        Integer total = (Integer) redisTemplate.opsForValue().get("total");
        if (total == null){
            total = 0;
        }
        //计算本月
        for (Date_MemberCount dmc : list) {
            Integer thisMonthCount = dmc.getCount() + total;
            dmc.setCount(dmc.getCount() + total);
            total = thisMonthCount;
        }

        return list;
    }

    @Override
    public BusinessReport getBusinessReportData() {
        Calendar calendar =Calendar.getInstance();
        String reportDate = calendar.get(Calendar.YEAR)+"-"+ (calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DATE);
        //今日新用户
        Integer todayNewMember = memberDao.getTodayNewMember();
        //本周新用户
        Integer thisWeekNewMember = memberDao.getThisWeekNewMember();
        //本月新用户
        Integer thisMonthNewMember = memberDao.getThisMonthNewMember();
        //总用户数量
        Integer totalMember = memberDao.getTotalMember();
        //今日预约数
        Integer todayOrderNumber = orderDao.getTodayOrderNumber();
        //本周预约数
        Integer thisWeekOrderNumber = orderDao.getThisWeekOrderNumber();
        //本月预约数
        Integer thisMonthOrderNumber = orderDao.getThisMonthOrderNumber();

        //hotSetMeal
        Integer count = orderDao.getAllOrdersCount();
        //仅查询前三的套餐
        List<Setmeal_Proportion> hotSetmeal=  setMealDao.getHotSetmeal(count);
        BusinessReport businessReport = new BusinessReport();
        businessReport.setReportDate(reportDate);
        businessReport.setTodayNewMember(todayNewMember);
        businessReport.setThisWeekNewMember(thisWeekNewMember);
        businessReport.setThisMonthNewMember(thisMonthNewMember);
        businessReport.setTotalMember(totalMember);
        businessReport.setTodayOrderNumber(todayOrderNumber);
        businessReport.setThisWeekOrderNumber(thisWeekOrderNumber);
        businessReport.setThisMonthOrderNumber(thisMonthOrderNumber);
        businessReport.setHotSetmeal(hotSetmeal);
        return businessReport;
    }


    @Override
    public void exportBusinessReport(HttpServletResponse response) throws Exception {
        //拿到excel模板对象
        ClassPathResource classPathResource = new ClassPathResource("reportTemplate/businessTemplate.xlsx");
        InputStream is = classPathResource.getInputStream();
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        ServletOutputStream os = response.getOutputStream();
        //处理excel中信息
        BusinessReport businessReportData = getBusinessReportData();
        XSSFSheet sheet = workbook.getSheetAt(0);
        //设置表中统计数据
        sheet.getRow(3).getCell(3).setCellValue(businessReportData.getReportDate());
        sheet.getRow(5).getCell(1).setCellValue(businessReportData.getTodayNewMember());
        sheet.getRow(5).getCell(3).setCellValue(businessReportData.getTotalMember());
        sheet.getRow(6).getCell(1).setCellValue(businessReportData.getThisMonthNewMember());
        sheet.getRow(6).getCell(3).setCellValue(businessReportData.getThisMonthNewMember());
        sheet.getRow(8).getCell(1).setCellValue(businessReportData.getTodayOrderNumber());
        sheet.getRow(8).getCell(3).setCellValue(businessReportData.getTodayVisitsNumber());
        sheet.getRow(9).getCell(1).setCellValue(businessReportData.getThisWeekOrderNumber());
        sheet.getRow(9).getCell(3).setCellValue(businessReportData.getThisWeekVisitsNumber());
        sheet.getRow(10).getCell(1).setCellValue(businessReportData.getThisMonthOrderNumber());
        sheet.getRow(10).getCell(3).setCellValue(businessReportData.getThisMonthVisitsNumber());
        //设置热门套餐数据
        List<Setmeal_Proportion> hotSetmeal = businessReportData.getHotSetmeal();
        if (hotSetmeal == null || hotSetmeal.size() <= 0){
            return;
        }
        Integer i = 13;
        for (Setmeal_Proportion sp : hotSetmeal) {
            //新建一行
            XSSFRow row = sheet.createRow(i);
            //新建三格子
            row.createCell(0).setCellValue(sp.getName());
            row.createCell(1).setCellValue(sp.getSetmeal_count());
            row.createCell(2).setCellValue(sp.getProportion().doubleValue());
            i++;
        }


        //响应下载操作
        response.setContentType("application/x-download");
        response.setCharacterEncoding("UTF-8");
        String date = ParseDateUtils.formatDate("yyyy-MM-dd",new java.util.Date());
        response.setHeader("Content-disposition", "attachment;filename=" + new String(("运营数据统计"+date).getBytes(), "ISO8859-1") + ".xlsx");
        workbook.write(os);
        os.flush();
        os.close();
        workbook.close();
        is.close();
    }
}
